package com.cl.pattern.memento.multiState;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.HashMap;

/**
 * @ClassName BeanUtils
 * @Description
 * @Author Small
 * @Date 2020/7/9 10:40
 * @Version 1.0
 **/
public class BeanUtils {

    /**
     * 备份属性值
     * @param obj
     * @return
     */
    public static HashMap<String, Object> backupProp(Object obj) {
        HashMap<String, Object> result = new HashMap<String, Object>();
        try {
            // 获得Bean描述
            BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
            // 获得属性描述
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            // 遍历所有属性
            for (PropertyDescriptor des : propertyDescriptors) {
                // 属性名称
                String fieldName = des.getName();
                // 读取属性的方法
                Method getter = des.getReadMethod();
                // 读取属性值
                Object fieldValue = getter.invoke(obj, new Object[]{});
                if (!fieldName.equalsIgnoreCase("class")) {
                    result.put(fieldName, fieldValue);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }


    /**
     * 恢复属性值
     * @param obj
     * @param propMap
     */
    public static  void restoreProp(Object obj,HashMap<String,Object> propMap){
        try{
            // 获得Bean的描述
            BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            for (PropertyDescriptor des:propertyDescriptors){
                // 属性名称
                String fieldName = des.getName();
                // 如果有这个属性
                if (propMap.containsKey(fieldName)){
                    Method setter = des.getWriteMethod();
                    setter.invoke(obj,new Object[] {propMap.get(fieldName)});
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
